package com.xywy.common;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.slidingmenu.lib.SlidingMenu;
import com.xywy.R;
import com.xywy.broadcast.RemindBroadCast;
import com.xywy.broadcast.RemindService;
import com.xywy.common.app.MainApplication;
import com.xywy.common.bean.ConnectedDevice;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.deviceparser.GetDeviceParser;
import com.xywy.common.greendao.BaseDao;
import com.xywy.common.manager.AppManager;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.sync.SyncBloodPresureDevice;
import com.xywy.common.sync.SyncWeightScaleData;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.ImageLoaderUtil;
import com.xywy.common.util.MD5Util;
import com.xywy.common.util.MLog;
import com.xywy.common.util.ToastUtil;
import com.xywy.find.FindActivity;
import com.xywy.find.RemindListActivity;
import com.xywy.find.bean.Remind;
import com.xywy.fwc.FwcActivity;
import com.xywy.fwc.FwcConstant;
import com.xywy.fwc.Utils;
import com.xywy.fwc.bean.FwcMessageBean;
import com.xywy.fwc.net.DataCallBack;
import com.xywy.fwc.net.Request;
import com.xywy.fwc.net.StringParser;
import com.xywy.me.CollectActivity;
import com.xywy.me.FeedbackActivity;
import com.xywy.me.InforActivity;
import com.xywy.me.SetupActivity;
import com.xywy.me.SetupPushActivity;
import com.xywy.me.bean.Jtcy;
import com.xywy.me.bean.User;
import com.xywy.me.bean.UserKeeper;
import com.xywy.wjk.MyDeviceActivity;
import com.xywy.wjk.WjkActivity;
import com.xywy.wjk.WjkMinVersonActivity;
import com.xywy.wjk.dao.BloodPressureDataDao;
import com.xywy.wjk.dao.WeightDataDao;
import com.xywy.wjk.util.WjkConstant;

/**
 * 名称: MainActivity 描述: 主activity 最近修改时间:2014-7-10 11:10
 * 
 * @author xgd
 */
public class FragmentMainActivity extends TabActivity implements
		OnClickListener {
	private TabHost tabHost;
	private LinearLayout ll_wjk;
	private LinearLayout ll_jtys;
	private LinearLayout ll_find;
	public static boolean CANTOUCH = true;
	
	private String wjkAddcontent; // 云健康中添加的数据

	public final static int FLAG_WEIGHT = 0X1101;


	private List<Remind> reminds; // 用來做發現裏面的提醒
	private RemindBroadCast remindReceiver;
	private SharedPreferences sp;
//	private Editor editor;
	private ImageView ivMessagePoint;
	private List<FwcMessageBean> messages;
	private ImageView iv_bottom_point;
	private int greenColor;
	private AppManager appManager;
	private User current_user;
	// 定义一个布局

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.fragemnt_main);
		appManager = AppManager.getInstance();
		appManager.addActivity(FragmentMainActivity.this);
		initView();
		initData();
		initReceiver();
	}

	public void initView() {
		tabHost = getTabHost();
		ll_wjk = (LinearLayout) findViewById(R.id.ll_wjk);
		ll_jtys = (LinearLayout) findViewById(R.id.ll_jtys);
		ll_find = (LinearLayout) findViewById(R.id.ll_find);
		
		ll_wjk.setOnClickListener(this);
		ll_jtys.setOnClickListener(this);
		ll_find.setOnClickListener(this);
		
		
		ll_main = (LinearLayout) findViewById(R.id.ll_main_bottom);
		iv_wjk = (ImageView) findViewById(R.id.iv_bottom_wjk);
		iv_jtys = (ImageView) findViewById(R.id.iv_bottom_jtys);
		iv_find = (ImageView) findViewById(R.id.iv_bottom_find);
		// iv_me = (ImageView) activity.findViewById(R.id.iv_bottom_me);

		tv_wjk = (TextView) findViewById(R.id.tv_bottom_wjk);
		tv_jtys = (TextView) findViewById(R.id.tv_bottom_jtys);
		tv_find = (TextView) findViewById(R.id.tv_bottom_find);
		
		greenColor = getResources().getColor(R.color.start_bt_bg);
		if (Build.VERSION.SDK_INT >= 18){
			TabSpec tabSpec = tabHost.newTabSpec("wjk");
			Intent intent = new Intent(this, WjkActivity.class);
			tabSpec.setIndicator("wjk");
			tabSpec.setContent(intent);
			 tabHost.addTab(tabSpec);  
		}else {
			TabSpec tabSpec = tabHost.newTabSpec("wjk");
			Intent intent = new Intent(this, WjkMinVersonActivity.class);
			tabSpec.setIndicator("wjk");
			tabSpec.setContent(intent);
			 tabHost.addTab(tabSpec);  
		}
		
		TabSpec tabSpec1 = tabHost.newTabSpec("fwc");
		Intent intent1 = new Intent(this, FwcActivity.class);
		tabSpec1.setIndicator("fwc");
		tabSpec1.setContent(intent1);
		
		
		TabSpec tabSpec2 = tabHost.newTabSpec("find");
		Intent intent2 = new Intent(this, FindActivity.class);
		tabSpec2.setIndicator("find");
		tabSpec2.setContent(intent2);
        //将Tab按钮添加进Tab选项卡中  
        tabHost.addTab(tabSpec1);  
        tabHost.addTab(tabSpec2);  
        tabHost.setCurrentTab(0);
	}

	
	
	
	
	private void initData(){
		MainApplication.setMainActivity(this);
		initDAO();
		current_user = UserKeeper.getCurrentUser(this);
		sp = getSharedPreferences("config", Context.MODE_PRIVATE);
//		editor = sp.edit();
//		userid = sp.getString("userid", "");
//		mobileNum = sp.getString("mobile", "");
		initSlidingMenu();
		loadData();
		initPushReceiver();
		startAlarm();
	}
	
	private WeightDataDao weightDataDao; // 体重数据操作
	private BloodPressureDataDao bloodPressureDataDao; // 体重数据操作

	private void initDAO() {
		BaseDao baseDao = BaseDao.getInstance(FragmentMainActivity.this);
		weightDataDao = baseDao.getWeightDataDao();
		bloodPressureDataDao = baseDao.getBloodPressureDataDao();
	}
	
	public void loadData() {
		/* 体重秤同步 */
		SyncWeightScaleData syncWeightScaleData = new SyncWeightScaleData(this, weightDataDao);
		
		syncWeightScaleData.syncDataFormServer();
		/* 血压计同步 */
		SyncBloodPresureDevice syncBloodPresureDevice = new  SyncBloodPresureDevice(this, bloodPressureDataDao);
		syncBloodPresureDevice.syncDataFormServer();
		
		getDeviceFromServer();
		getFwcMessages();
	}
	
	/**
	 * 接收消息推送用的
	 * 
	 */
	private void initPushReceiver() {
		Resources resource = this.getResources();
		String pkgName = this.getPackageName();
		PushManager.startWork(getApplicationContext(),
				PushConstants.LOGIN_TYPE_API_KEY,
				Utils.getMetaValue(this, "api_key"));
		IntentFilter filter = new IntentFilter(
				"com.baidu.android.pushservice.action.notification.SHOW");
		filter.addAction("pushbind");
		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent intent) {
				Log.e("baiduyunpush---", intent.getAction());
				int isPush = sp.getInt(current_user.getUserid() + SetupPushActivity.PUSHSTATE, SetupPushActivity.PUSH);
				
				if (isPush == SetupPushActivity.UNPUSH) {
					return;
				}
				if (intent
						.getAction()
						.equals("com.baidu.android.pushservice.action.notification.SHOW")) {
					ivMessagePoint.setVisibility(View.VISIBLE);
				}
			}
		}, filter);
	}

	
	private void initRemind(){
		int remindFlag = sp.getInt("remind", -1);
		if (remindFlag == -1) {
			// 这个时候证明已经还没有添加那个消息提醒
			Remind remind = new Remind();
			remind.setType(2);
			String hint = getString(R.string.find_remind_cztx);
			remind.setHint(hint);
			int check[] = new int[7];
			for (int i = 0; i < check.length; i++) {
				check[i] = i;
			}
			remind.setLooparray(check);
			remind.setTogglet(true);
			Calendar c = Calendar.getInstance();
			c.set(Calendar.HOUR_OF_DAY, 8);
			c.set(Calendar.MINUTE, 0);
			remind.setTime(c.getTimeInMillis());
			List<Remind> list = new ArrayList<Remind>();
			list.add(remind);
			FileUtil.saveObjectList(current_user.getUserid() + "reminds", list);
			sp.edit().putInt("remind", 1).commit();
		} else {
			// 这个时候已经添加过了
		}
	}
	
	void startAlarm(){
		Intent intent = new Intent(this,RemindService.class);
		startService(intent);
	}
	
	
	private SlidingMenu slidingMenu;
	private boolean mUserInfoFlag = false;
	JSONObject msgBack = null;
	// 封装Parser参数
	private Parser paramsParser;
	// 封装httpclient参数
	private HashMap<String, Object> params;
	// 异步加载
	private AsyncHttpClient asyncHttpClient;
//	private String userid = "";

	/** 家庭成员列表 */
	private List<Jtcy> jtcys; // 返回的所有用户数据
	protected String userIconStr = "";
	protected ImageView userIcon;
	protected TextView account;
	protected String mobile = "";
	protected TextView nick;
	// ====ImageLoader start====
	public static final List<String> displayedImages = Collections
			.synchronizedList(new LinkedList<String>());

//	private Jtcy mainAccout = new Jtcy();
//	private String mainNick = "";
//	private String mobileNum;
	
	
	/** 初始化slidingMenu */
	private void initSlidingMenu() {
		slidingMenu = new SlidingMenu(this);
		slidingMenu.setBackgroundImage(R.drawable.sliding_menu_background);
		// slidingMenu.setShadowDrawable(R.drawable.shadow_shape);
		slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		slidingMenu.setFadeEnabled(false);

		slidingMenu.setBehindScrollScale(0.25f);
		slidingMenu.setFadeDegree(0.25f);
		slidingMenu
				.setBehindCanvasTransformer(new SlidingMenu.CanvasTransformer() {

					@Override
					public void transformCanvas(Canvas canvas, float percentOpen) {
						// TODO Auto-generated method stub
						float scale = (float) (percentOpen * 0.25 + 0.75);
						canvas.scale(scale, scale, -canvas.getWidth() / 2,
								canvas.getHeight() / 2);
					}

				});
		slidingMenu
				.setAboveCanvasTransformer(new SlidingMenu.CanvasTransformer() {

					@Override
					public void transformCanvas(Canvas canvas, float percentOpen) {
						// TODO Auto-generated method stub
						float scale = (float) (1 - percentOpen * 0.25);
						canvas.scale(scale, scale, 0, canvas.getHeight() / 2);
					}
				});
		slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		slidingMenu.setMode(SlidingMenu.LEFT);
		slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_WINDOW);
		slidingMenu.setMenu(R.layout.fragment_me);

		// 我相关的信息
		findViewById(R.id.rl_me_infor).setOnClickListener(this);
		userIcon = (ImageView) this.findViewById(R.id.me_cover_user_photo);
		account = (TextView) this.findViewById(R.id.tv_me_account);
		nick = (TextView) this.findViewById(R.id.tv_account_nick);

		account.setText(current_user.getPhonenum());
		// 我的设备
		this.findViewById(R.id.rl_me_mydevice).setOnClickListener(this);
		// 我的收藏
		this.findViewById(R.id.rl_me_wdsc).setOnClickListener(this);
		// 我的提醒
		this.findViewById(R.id.rl_me_wdtx).setOnClickListener(this);
		// 设置
		this.findViewById(R.id.tv_slidingmenu_setting).setOnClickListener(this);
		// 反馈
		this.findViewById(R.id.tv_slidingmenu_feedback)
				.setOnClickListener(this);
		// sendMsg();
//		mainAccout = FileUtil.getCurrentUser(userid + "mainaccount");
//		if (mainAccout != null) {
		setUserInfo();
//		} else {
//			sendMsg();
//		}
	}
		
		/**
		 * 返回
		 */
//		private Handler handler = new Handler() {
//			@Override
//			public void handleMessage(Message msg) {
//				super.handleMessage(msg);
//				MLog.e("handler-----", "back:" + msg.obj + "resuletCode:" + msg.arg1);
//				// myProgress.stop();
//				if (msg.arg1 == ResultCode.SUCCESS) {
//					try {
//						if (msg.obj != null) {
//							msgBack = new JSONObject(msg.obj.toString());
//							if (msgBack == null)
//								return;
//						} else {
//							setUserInfo();
//							return;
//						}
//					} catch (JSONException e) {
//						e.printStackTrace();
//						return;
//					}
//					if (msgBack.optInt("state") == ResultCode.SUCCESS) {
//						mUserInfoFlag = true;
//						// 解析返回的数据
//						userIconStr = msgBack.optString("avatar");
//						String email = msgBack.optString("email");
//						if (!userIconStr.endsWith(".jpg")) { // 判断是否以.jpg结尾
//							userIconStr += ".jpg";
//							// imageLoader.displayImage(userIconStr, imageView)
//						}
//						mainAccout = UserKeeper.getCurrentUser();
//						mainAccout.setIcon(userIconStr);
//						Log.e("hhaha", userIconStr);
//						jtcys = jsonAny(msg.obj.toString());
//						nick.setText(mainNick);
//						circleImageView(userIconStr, userIcon);
//						// account.setText(mobile);
//					} else {
//						setUserInfo();
//						Toast.makeText(FragmentMainActivity.this,
//								msgBack.optString("error"), Toast.LENGTH_LONG)
//								.show();
//					}
//				} else {
//					setUserInfo();
//					Toast.makeText(FragmentMainActivity.this,
//							getString(R.string.common_net_fail), Toast.LENGTH_LONG)
//							.show();
//				}
//
//			}
//
//		};
	
	
	void setUserInfo() {
//		mainAccout = FileUtil.getCurrentUser(userid + "mainaccount");
//		if (mainAccout != null) {
		nick.setText(current_user.getAccountstr());
		circleImageView(current_user.getAvatar(), userIcon);
//		UserKeeper.setCurrentUser(mainAccout);
//		}
	}
	
	private void circleImageView(String url, ImageView imageView) {
		// 圆形头像
		ImageLoaderUtil.displayHeadImage(url, imageView);
		Intent intent = new Intent(WjkConstant.IMAGE_URL);
		intent.putExtra("url", url);
		sendBroadcast(intent);
	}
	
	/**
	 * 获取设备通过userid  同步 进行同步
	 */
	public static final String getDevcieUrl = "http://api.yun.xywy.com/index.php/server/api/equipment/list_data/";
	 
	private void getDeviceFromServer(){
	     //同步上传
		Log.e("getdeviceurl    ", getDevcieUrl+current_user.getUserid());
		Request.requestData(new GetDeviceParser(), getDeviceCall, getDevcieUrl+current_user.getUserid());
	 }
	
	DataCallBack<String> getDeviceCall = new DataCallBack<String>() {
		
		@Override
		public void dataCall(String t) {
			// TODO Auto-generated method stub
			try {
				if(t == null){
					//没有网络  或者请求失败的时候
					return;
				}
				JSONObject json = new JSONObject(t);
				int status = json.optInt("status");
				if(status ==0){
					JSONArray data = json.optJSONArray("data");
					for(int i=0;i<data.length();i++){
						JSONObject dataItem = (JSONObject) data.get(i);
						 String de_string = dataItem.optString("de_string");
						 String de_timestamp = dataItem.optString("de_timestamp");
						 if("Xunyiwenyao".equals(de_string)){
							 
							 long serviceTime = Long.parseLong(de_timestamp)*1000;
							 ConnectedDevice weight_device = FileUtil.getWeightDevice();
							 long localTime = weight_device.getConnect_time();
							 if(localTime <serviceTime){
								 weight_device.setConnect_time(serviceTime);
							 }
							 FileUtil.saveWeightDevice(weight_device);
						 }else if (de_string != null && de_string.startsWith("KBB")) {
							 ConnectedDevice blood_device = FileUtil.getBloodDevice();
							long localTime = blood_device.getConnect_time();
							 long serviceTime = Long.parseLong(de_timestamp)*1000;
							 if(localTime <serviceTime){
								 blood_device.setConnect_time(serviceTime);
							 }
							 FileUtil.saveBloodDevice(blood_device);
						}
					}
					Intent intent = new Intent(WjkConstant.GET_DEVICE);
					sendBroadcast(intent);
				}else {
					//这个时侯 没有数据
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	
	/**
	 * 第一次加载要获取服务窗
	 */
	private void getFwcMessages() {
		try {
			HashMap<Object, Object> params = new HashMap<Object, Object>();
			params.put("xywy_userid", current_user.getUserid());
			params.put("sign", MD5Util.md5("KHy69gsk8%#@kl$zj"));
			params.put("tag", "zj");
			Request.postData(new StringParser(), call_push, FwcConstant.PUSh_URL, params);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private String mSign; // 签名
	private String mSignUrl = "http://api.yun.xywy.com/index.php/server/api/service_provider/create_sn//"; //获取签名

	DataCallBack<String> call_push = new DataCallBack<String>() {
		
		@Override
		public void dataCall(String str) {
			FwcConstant.keepFwcMessages(str, FragmentMainActivity.this);
			if(FwcConstant.getMessageCount(FwcConstant.FWC_MESSAGE, FragmentMainActivity.this)>0){
				runOnUiThread(new  Runnable() {
					public void run() {
						iv_bottom_point.setVisibility(View.VISIBLE);
					}
				});
			}
		}
	};
	
	/**
	 * 服务窗消息handler
	 */
	private Handler fwcHandler = new Handler() {
		public void handleMessage(Message msg) {
			ivMessagePoint.setVisibility(View.VISIBLE);
		};
	};
	/**
	 * 服务窗回掉
	 */
	DataCallBack<List<FwcMessageBean>> callable = new DataCallBack<List<FwcMessageBean>>() {

		@Override
		public void dataCall(List<FwcMessageBean> t) {
			// TODO Auto-generated method stub
			if (t != null && t.size() > 0) {
				if (messages == null) {
					messages = new ArrayList<FwcMessageBean>();
				}
				messages.addAll(t);
				FileUtil.saveObject(current_user.getUserid() + FileUtil.FWC_MESSAGES, messages);
				fwcHandler.sendEmptyMessage(0);
			}
		}
	};
	
//	private List<Jtcy> jsonAny(String jsonStr) {
//
//		List<Jtcy> list = Collections.synchronizedList(new ArrayList<Jtcy>());
//		// 分别实例化，进行潜拷贝
//		Jtcy jtcy = new Jtcy();
//		try {
//			JSONObject jsonObject = new JSONObject(jsonStr);
//			JSONArray jsonArray = jsonObject.getJSONArray("accounts");
//			if (null != jsonArray && jsonArray.length() > 0) {
//				for (int i = 0; i < jsonArray.length(); i++) {
//					JSONObject json = jsonArray.getJSONObject(i);
//					Jtcy cy = jtcy.clone();
//
//					cy.setAccountid(json.optLong("accountid"));
//					cy.setAccountstr(json.optString("accountstr"));
//					cy.setSex(json.optString("sex"));
//					cy.setHeight(json.optString("height"));
//					cy.setBirthday(json.optString("birthday"));
//
//					if (json.optInt("accountid") == 0) {
//						// mainAccout = cy;
//						mainNick = json.optString("accountstr");
//						mainAccout.setName(mainNick);
//						mainAccout.setAccountid(json.optLong("accountid"));
//						mainAccout.setAccountstr(mainNick);
//						mainAccout.setBirthday(json.optString("birthday"));
//						mainAccout.setHeight(json.optString("height"));
//						mainAccout.setSex(json.optString("sex"));
//						FileUtil.saveCurrentUser(userid + "mainaccount",
//								mainAccout);
//						UserKeeper.setCurrentUser(mainAccout);
//					}
//					// 存储到本地db
//					list.add(cy);
//					/*
//					 * dao.deleteAll(); long ret= dao.insert(cy);
//					 * MLog.i(TAG,"存储到本地db :"+ret);
//					 */
//				}
//			}
//		} catch (JSONException e) {
//			e.printStackTrace();
//		}
//		return list;
//	}
	
	
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		

		case R.id.ll_wjk:
			clearBottomBar();
			tabHost.setCurrentTab(0);
			showwjkBottom();
			
			break;
		case R.id.ll_jtys:
			clearBottomBar();
			tabHost.setCurrentTab(1);
			showJTYSBottom();
			break;
		case R.id.ll_find:
			clearBottomBar();
			tabHost.setCurrentTab(2);
			showFindBottom();
			break;
		
		case R.id.iv_wjk_left_sliding_menu_icon:
			// 侧滑栏按钮
			slidingMenu.showMenu(5000);
			break;
		case R.id.wjk_circle_view:
			// Intent tzDetailIntent = new Intent(this,
			// WjkDetailActivity.class);
			// startActivity(tzDetailIntent);
			break;
		case R.id.btn_yjk_second:
			break;
		case R.id.btn_yjk_third:
			break;

		// slidingMenu相关的点击事件
		case R.id.rl_me_infor:
			// 账户信息
			Intent infontent = new Intent(this, InforActivity.class);
//			infontent.putExtra("jtcy", mainAccout); // 主用户信息
			startActivity(infontent);
			break;
		case R.id.rl_me_mydevice:
			// 我的设备
			if (Build.VERSION.SDK_INT >= 18){
				Intent myDeviceIntent = new Intent(this, MyDeviceActivity.class);
				startActivity(myDeviceIntent);
			}else {
				WjkMinVersonActivity.showMinToast(this);
			}
			// startActivityForResult(myDeviceIntent, FLAG_WEIGHT);
			break;
		case R.id.rl_me_wdsc:
			// 我的收藏
			Intent myCollectIntent = new Intent(this, CollectActivity.class);
			startActivity(myCollectIntent);

			break;
		case R.id.rl_me_wdtx:
			// 我的提醒
			Intent myRemindIntent = new Intent(this, RemindListActivity.class);
			startActivity(myRemindIntent);
			break;
		case R.id.tv_slidingmenu_setting:
			// 设置
			Intent setupIntent = new Intent(this, SetupActivity.class);
			startActivity(setupIntent);
			break;
		case R.id.tv_slidingmenu_feedback:
			// 反馈
			Intent feedbackIntent = new Intent(this, FeedbackActivity.class);
			startActivity(feedbackIntent);
			break;
		}

	}
	
	private void initReceiver(){
		IntentFilter filter = new IntentFilter(WjkConstant.OPEN_SLIDE);
		filter.addAction(WjkConstant.CLOSE_SLIDE);
		registerReceiver(new SlideReceiver(), filter);
	}
	
	class SlideReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context arg0, Intent intent) {
			String action = intent.getAction();
			if(WjkConstant.OPEN_SLIDE.equals(action)){
				slidingMenu.showMenu(5000);
			}else if (WjkConstant.CLOSE_SLIDE.equals(action)) {
				closeSlidingMenu();
			}
		}
		
	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		if (!CANTOUCH) {
			ToastUtil.showToast(this, "正在测量请稍后", 1);
			return CANTOUCH;
		} else {
			return super.dispatchTouchEvent(ev);
		}
	}
	
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		  if(event.getKeyCode() == KeyEvent.KEYCODE_BACK  
		            && event.getAction() == KeyEvent.ACTION_DOWN  
		            ){
				if (CANTOUCH){
					exit();
				}
		     return true;
		  }
		return super.dispatchKeyEvent(event);
	}
	
	
	
	private LinearLayout ll_main;

	private ImageView iv_wjk;
	private ImageView iv_jtys;
	private ImageView iv_find;
	// private ImageView iv_me;

	private TextView tv_wjk;
	private TextView tv_jtys;
	private TextView tv_find;
	
	/**
	 * 微健康
	 */
	private void showwjkBottom() {
		changeBottomVisiblity(View.VISIBLE);
		iv_wjk.setBackgroundResource(R.drawable.main_wjk_pressed);
		tv_wjk.setTextColor(greenColor);
	}

	/**
	 * 家庭医生
	 */
	private void showJTYSBottom() {
		changeBottomVisiblity(View.VISIBLE);

		iv_jtys.setBackgroundResource(R.drawable.main_jtys_pressed);
		tv_jtys.setTextColor(greenColor);
	}

	/**
	 * 发现
	 */
	private void showFindBottom() {
		changeBottomVisiblity(View.VISIBLE);
		iv_find.setBackgroundResource(R.drawable.main_fx_pressed);
		tv_find.setTextColor(greenColor);
	}
	
	/**
	 * 改变底部导航容器显示情况
	 */
	public void changeBottomVisiblity(int type) {
		if (ll_main.getVisibility() != type)
			ll_main.setVisibility(type);
	}
	
	
	private void clearBottomBar() {
		iv_wjk.setBackgroundResource(R.drawable.main_wjk);
		iv_jtys.setBackgroundResource(R.drawable.main_jtys);
		iv_find.setBackgroundResource(R.drawable.main_fx);
		// iv_me.setBackgroundResource(R.drawable.main_wo_pressed);

		// int whiteColor = mActivity.getResources().getColor(R.color.white);
		int bottom_font_color = getResources().getColor(R.color.yjk_bottom_font_color);
		tv_wjk.setTextColor(bottom_font_color);
		tv_jtys.setTextColor(bottom_font_color);
		tv_find.setTextColor(bottom_font_color);
		// tv_me.setTextColor(Color.WHITE);
	}
	
	public void closeSlidingMenu() {
		if (slidingMenu.isMenuShowing()) {
			slidingMenu.toggle();
		}
	}
	
	
	/**
	 * 二次点击退出应用
	 */
	private void exit() {
		if (!isExit) {
			isExit = true;
			Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
			exitHandler.sendEmptyMessageDelayed(0, 2000);
		} else {
			MainApplication.getInstance().exit();
			appManager.finishAllActivity();
		}
	}
	
	private Boolean isExit = false;

	/**
	 * 退出应用exitHandler
	 */
	private Handler exitHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			isExit = false;
			super.handleMessage(msg);
		}
	};

}
